using Microsoft.EntityFrameworkCore;
using Net8.Identity.Server.Models;

namespace Net8.Identity.Server.Services
{
    /// <summary>
    /// CORS配置服务
    /// </summary>
    public class CorsSettingsService
    {
        private readonly IServiceProvider _serviceProvider;

        public CorsSettingsService(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }

        /// <summary>
        /// 获取CORS配置
        /// </summary>
        /// <returns>CORS配置列表</returns>
        public async Task<List<CorsSetting>> GetCorsSettingsAsync()
        {
            using var scope = _serviceProvider.CreateScope();
            var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
            
            // 确保数据库已创建
            await dbContext.Database.EnsureCreatedAsync();
            
            // 获取所有CORS配置
            var settings = await dbContext.CorsSettings.ToListAsync();
            
            // 如果没有配置，则创建默认配置
            if (!settings.Any())
            {
                var defaultSetting = new CorsSetting
                {
                    PolicyName = "AllowSpecificOrigins",
                    AllowedOrigins = "https://localhost:7164,https://localhost:7002",
                    AllowCredentials = true,
                    AllowAnyHeader = true,
                    AllowAnyMethod = true
                };
                
                dbContext.CorsSettings.Add(defaultSetting);
                await dbContext.SaveChangesAsync();
                
                settings.Add(defaultSetting);
            }
            
            return settings;
        }
    }
}